#include "StdAfx.h"

#include "Server.h"

#include "AsioChannel.h"
#include "ServerPI.h"
#include "Log.h"

#include <iostream>

namespace ftp
{

Server::Server(int port, FileSystem* fileSystem)
	: m_fileSystem(fileSystem)
{
	m_acceptor.reset(new tcp::acceptor(m_ioService, tcp::endpoint(tcp::v4(), port), true));

	acceptServerPI();
}

void Server::run()
{
	m_ioService.run();
}

//ServerPI Management

void Server::onAcceptServerPiSocket(SocketSPtr socket, const boost::system::error_code& error)
{
	LOG() << std::endl;

	if (error)
	{
		LOG_ERROR() << error.message() <<  std::endl;
		return;
	}
	
	std::auto_ptr<IChannel> newChannel(new AsioChannel(socket));
	std::auto_ptr<ServerPI> newServerPI(new ServerPI(newChannel, m_fileSystem));
	m_serverPIs.push_back(newServerPI);

	acceptServerPI();
}

void Server::acceptServerPI()
{
	SocketSPtr newSocket(new tcp::socket(m_ioService));
	m_acceptor->async_accept(*newSocket, boost::bind(&Server::onAcceptServerPiSocket, this, newSocket, ba::placeholders::error));
}

} //ftp
